package com.itg.vms.util;

import com.itg.vms.entity.vo.MenuVo;

import java.util.ArrayList;
import java.util.List;

/**
 * @create 2023年03月07日 01:37:14
 */
public class TreeUtil {

    /**
     * 扎转换为树结构
     * @param treeList 菜单视图列表
     * @param pid
     * @return 视图列表
     */
    public static List<MenuVo> toTree(List<MenuVo> treeList, Long pid) {
        List<MenuVo> retList = new ArrayList<MenuVo>();
        for (MenuVo parent : treeList) {
            if (pid.equals(parent.getPid())) {
                retList.add(findChildren(parent, treeList));
            }
        }

        return retList;
    }

    /**
     * 找到子菜单
     * @param parent 父类视图菜单
     * @param treeList 菜单树
     * @return 菜单视图
     */
    private static MenuVo findChildren(MenuVo parent, List<MenuVo> treeList) {
        for (MenuVo child : treeList) {
            if (parent.getId().equals(child.getPid())) {
                if (parent.getChild() == null) {
                    parent.setChild(new ArrayList<>());
                }
                parent.getChild().add(findChildren(child, treeList));
            }
        }
        return parent;
    }
}
